<template>
	<view class="container">
		<!-- 筛选标签 -->
		<view class="filter-tabs">
			<view 
				class="tab-item" 
				:class="{ active: currentTab === 'all' }"
				@click="switchTab('all')"
			>全部</view>
			<view 
				class="tab-item" 
				:class="{ active: currentTab === 'normal' }"
				@click="switchTab('normal')"
			>未逾期</view>
			<view 
				class="tab-item" 
				:class="{ active: currentTab === 'overdue' }"
				@click="switchTab('overdue')"
			>已逾期</view>
		</view>

		<!-- 待还款列表 -->
		<view class="loan-list">
			<view class="section-title">
				{{ currentTab === 'all' ? '全部待还款' : 
					currentTab === 'normal' ? '未逾期待还款' : '已逾期待还款' }}
			</view>
			<template v-if="loading">
				<view class="loan-item skeleton" v-for="i in 10" :key="i">
					<view class="loan-info">
						<view class="skeleton-amount"></view>
						<view class="skeleton-text"></view>
						<view class="skeleton-text"></view>
						<view class="skeleton-text"></view>
					</view>
					<view class="skeleton-btn"></view>
				</view>
			</template>
			<view v-else-if="filteredLoans.length > 0">
				<view 
					v-for="(loan, index) in filteredLoans" 
					:key="index"
					class="loan-item"
				>
					<view class="loan-info">
						<view class="loan-amount">¥{{ loan.amount }}</view>
						<view class="loan-date">借款日期：{{ loan.date }}</view>
						<view class="loan-term">期限：{{ loan.term }}天</view>
						<view class="loan-status" :class="loan.status === '已逾期' ? 'overdue' : ''">
							状态：{{ loan.status }}
							<text v-if="loan.status === '已逾期'" class="overdue-days">
								(已逾期{{ loan.overdue_days }}天)
							</text>
						</view>
						<view v-if="loan.status === '已逾期'" class="overdue-amount">
							逾期费用：¥{{ loan.overdue_amount || 0 }}
						</view>
					</view>
					<button 
						class="repay-btn"
						:class="{'overdue-btn': loan.status === '已逾期'}"
						@click="handleRepay(loan, index)"
						v-if="loan.canRepay"
					>
						{{ loan.status === '已逾期' ? '逾期还款' : '立即还款' }}
					</button>
				</view>
			</view>
			<view v-else-if="!loading" class="empty-tip">
				暂无待还款项
			</view>
		</view>

		<!-- 还款方式选择弹窗 -->
		<view class="popup-mask" v-if="showPopup" @click="closePopup"></view>
		<view class="popup-content" v-if="showPopup">
			<view class="popup-title">选择还款方式</view>
			<view class="payment-methods">
				<view 
					class="payment-item"
					v-for="method in paymentMethods"
					:key="method.id"
					:class="{ 'disabled': method.disabled }"
					@click="method.disabled ? null : handlePaymentSelect(method)"
				>
					<image :src="method.icon" mode="aspectFit"></image>
					<text>{{ method.name }}</text>
				</view>
			</view>
			<button class="cancel-btn" @click="closePopup">取消</button>
		</view>
	
		<!-- 还款按钮弹窗 -->
		<uni-link text="点击去浏览器打开" v-if="href != ''" :href="href"></uni-link>
	</view>
</template>

<script setup>
import { ref, onMounted, computed  } from 'vue'
import request from "@/common/request.js"
import { STORAGE_KEY } from '../../common/config';
const showPopup = ref(false)
const pendingLoans = ref([])
let currentLoan = ref(null)
const loading = ref(true)
let href = ref("");
const currentTab = ref('all') // 当前选中的标签

const paymentMethods = [
	{ id: 1, name: '支付宝支付', icon: request.baseURL + 'media/default/支付宝.png' },
	{ 
		id: 2, 
		name: '微信支付(暂未开通)', 
		icon: request.baseURL + 'media/default/微信支付.png',
		disabled: true 
	},
	{ 
		id: 3, 
		name: '银行卡支付(暂未开通)',
		icon: request.baseURL + 'media/default/银行卡支付 .png',
		disabled: true 
	},
]

// 根据标签筛选贷款
const filteredLoans = computed(() => {
	switch(currentTab.value) {
		case 'normal':
			return pendingLoans.value.filter(loan => loan.status === '已放款')
		case 'overdue':
			return pendingLoans.value.filter(loan => loan.status === '已逾期')
		default:
			return pendingLoans.value
	}
})

// 切换标签
const switchTab = (tab) => {
	currentTab.value = tab
}

// 获取待还款列表
const loadPendingLoans = (data) => {
	loading.value = true
	const records = uni.getStorageSync(STORAGE_KEY.LOAN_RECORDS) || '[]'
	const recordsArray = JSON.parse(records)
	
	// 转换数据格式
	pendingLoans.value = data.map(record => {
		// 根据status映射状态文本
		let statusText = ''
		let canRepay = false
		
		// 计算逾期天数
		let overdueDays = 0
		if (record.repayment_time) {
			const repayDate = new Date(record.repayment_time)
			const today = new Date()
			// 设置时间为 00:00:00，只比较日期
			repayDate.setHours(0, 0, 0, 0)
			today.setHours(0, 0, 0, 0)
			
			const diffTime = today.getTime() - repayDate.getTime()
			const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
			
			if (diffDays > 0) {
				overdueDays = diffDays
			}
		}
		
		switch(record.status) {
			case 0:
				statusText = '待审核'
				canRepay = false
				break
			case 1:
				statusText = '已通过'
				canRepay = false
				break
			case 2:
				statusText = '已拒绝'
				canRepay = false
				break
			case 3:
				statusText = '已放款'
				// 如果已经逾期，更新状态
				if (overdueDays > 0) {
					statusText = '已逾期'
					record.status = 5
				}
				canRepay = true
				break
			case 4:
				statusText = '已还款'
				canRepay = false
				break
			case 5:
				statusText = '已逾期'
				canRepay = true
				break
			case 6:
				statusText = '已流标'
				canRepay = false
				break
		}
		
		return {
			amount: record.amount || 1,
			date: record.create_time,
			loan_order_number: record.loan_order_number,
			status: statusText,
			canRepay: canRepay,
			term: record.loan_time || 7,
			overdue_days: overdueDays,
			repayment_time: record.repayment_time,
			overdue_amount: record.overdue_amount,
			description: record.description,
			user_info: record.user_info
		}
	}).filter(record => record.canRepay) // 只显示可以还款的记录
	
	setTimeout(() => {
		loading.value = false
	}, 1000)
}

// 处理还款
const handleRepay = (loan, index) => {
	currentLoan.value = loan
	
	// 检查是否逾期
	if (loan.overdue_days > 0) {
		uni.showToast({
			title: `已逾期${loan.overdue_days}天`,
			icon: 'none'
		})
	}
	
	showPopup.value = true
}

// 处理支付方式选择
const handlePaymentSelect = async (method) => {
	showPopup.value = false
	
	uni.showLoading({
		title: '处理中...'
	})
	
	try {
		// 计算总还款金额(本金 + 逾期费用)
		const totalAmount = Number(currentLoan.value.amount) + 
							Number(currentLoan.value.overdue_amount || 0)
		method.loan_order_number = currentLoan.value.loan_order_number;
		method.pay_type = "0"
		method.money = totalAmount
		console.log(method);
		// 这里应该调用实际的还款接口
		request.post("api/pay/pay/", method, {success: "开始支付"}).then(res => {}).catch(err => {
			if(err.data.data.code == 1) {
				let pay_url = err.data.data.payurl;
				href.value = pay_url;
			}
			
		})
		
		
		// 更新本地存储
		// const records = uni.getStorageSync(STORAGE_KEY.LOAN_RECORDS) || '[]'
		// const recordsArray = JSON.parse(records)
		// const index = recordsArray.findIndex(r => r.loan_order_number === currentLoan.value.loan_order_number)
		
		// if (index !== -1) {
		// 	recordsArray[index].status = 1 // 已还款
		// 	recordsArray[index].repayment_time = new Date().toISOString().split('T')[0]
		// 	uni.setStorageSync(STORAGE_KEY.LOAN_RECORDS, JSON.stringify(recordsArray))
		// }
		
		// uni.showToast({
		// 	title: '还款成功',
		// 	icon: 'success'
		// })
		
		// loadPendingLoans()
		
	} catch (error) {
		uni.showToast({
			title: '还款失败，请重试',
			icon: 'none'
		})
	} finally {
		uni.hideLoading()
	}
}

const closePopup = () => {
	showPopup.value = false
}

// 获取我的待还款
const get_order = () => {
	loading.value = true
	// 获取已放款和已逾期的订单
	request.get("api/loan/select/my_order/", {status: [3, 5]}).then(res => {
		loadPendingLoans(res.data)
	}).catch(err => {
		uni.showToast({
			title: '加载失败，请重试',
			icon: 'none'
		})
	}).finally(() => {
		loading.value = false
	})
}

onMounted(() => {
	get_order()
	
})
</script>

<style lang="scss" scoped>
.filter-tabs {
	display: flex;
	background-color: #fff;
	padding: 20rpx 30rpx;
	margin-bottom: 20rpx;
	border-radius: 20rpx;
	
	.tab-item {
		flex: 1;
		text-align: center;
		font-size: 28rpx;
		color: #666;
		padding: 15rpx 0;
		position: relative;
		
		&.active {
			color: #4A90E2;
			font-weight: bold;
			
			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 40rpx;
				height: 4rpx;
				background-color: #4A90E2;
				border-radius: 2rpx;
			}
		}
	}
}

.container {
	padding: 30rpx;
	background-color: #f5f7fa;
	min-height: 100vh;
}

.loan-list {
	background-color: #fff;
	border-radius: 20rpx;
	padding: 30rpx;
	
	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 30rpx;
		color: #333;
	}
	
	.loan-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #eee;
		
		&:last-child {
			border-bottom: none;
		}
		
		.loan-info {
			.loan-amount {
				font-size: 40rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 10rpx;
			}
			
			.loan-date, .loan-term {
				font-size: 24rpx;
				color: #999;
				margin-top: 6rpx;
			}
			
			.loan-status {
				font-size: 24rpx;
				color: #666;
				margin-top: 6rpx;
				
				&.overdue {
					color: #ff4d4f;
				}
				
				.overdue-days {
					margin-left: 10rpx;
					font-weight: bold;
				}
			}
			
			.overdue-amount {
				font-size: 24rpx;
				color: #ff4d4f;
				margin-top: 6rpx;
				font-weight: bold;
			}
		}
		
		.repay-btn {
			background-color: #4A90E2;
			color: #fff;
			font-size: 28rpx;
			padding: 15rpx 40rpx;
			border-radius: 30rpx;
			margin: 0;
			
			&.overdue-btn {
				background-color: #ff4d4f;
			}
		}
	}
	
	.empty-tip {
		text-align: center;
		color: #999;
		font-size: 28rpx;
		padding: 100rpx 0;
	}
	
	.skeleton {
		.loan-info {
			.skeleton-amount {
				width: 200rpx;
				height: 40rpx;
				background: #f5f5f5;
				border-radius: 4rpx;
				margin-bottom: 20rpx;
				animation: skeleton-loading 1.5s infinite;
			}
			
			.skeleton-text {
				width: 300rpx;
				height: 24rpx;
				background: #f5f5f5;
				border-radius: 4rpx;
				margin-top: 16rpx;
				animation: skeleton-loading 1.5s infinite;
				
				&:nth-child(2) { width: 250rpx; }
				&:nth-child(3) { width: 200rpx; }
				&:nth-child(4) { width: 150rpx; }
			}
		}
		
		.skeleton-btn {
			width: 160rpx;
			height: 60rpx;
			background: #f5f5f5;
			border-radius: 30rpx;
			animation: skeleton-loading 1.5s infinite;
		}
	}
}

.popup-mask {
	position: fixed;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	background: rgba(0, 0, 0, 0.4);
	z-index: 998;
}

.popup-content {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0;
	padding: 30rpx;
	z-index: 999;
	
	.popup-title {
		text-align: center;
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 30rpx;
	}
	
	.payment-methods {
		.payment-item {
			display: flex;
			align-items: center;
			padding: 30rpx 0;
			border-bottom: 1rpx solid #eee;
			
			&.disabled {
				opacity: 0.5;
				cursor: not-allowed;
			}
			
			image {
				width: 60rpx;
				height: 60rpx;
				margin-right: 20rpx;
			}
			
			text {
				font-size: 30rpx;
				color: #333;
			}
		}
	}
	
	.cancel-btn {
		margin-top: 30rpx;
		background-color: #f5f5f5;
		color: #666;
		border-radius: 45rpx;
	}
}

@keyframes skeleton-loading {
	0% {
		background: #f5f5f5;
	}
	50% {
		background: #eee;
	}
	100% {
		background: #f5f5f5;
	}
}
</style> 